﻿using System;
using System.Collections.Generic;
using Google.GData.Client;

namespace BloggerAutoPosterService.Engine.Net
{
    public class BloggerAutoPoster
    {
        #region Properties (7)

        public string BlogUrl { set; get; }

        public string Password { set; get; }

        public bool PostAsDraft { set; get; }

        public string PostBody { set; get; }

        public IList<string> PostTags { set; get; }

        public string PostTitle { set; get; }

        public string UserName { set; get; }

        #endregion Properties

        #region Methods (2)

        // Public Methods (1) 

        public bool PostNewEntry()
        {
            var service = new Service("blogger", "blogger-example")
            {
                Credentials = new GDataCredentials(UserName, Password)
            };
            var newPost = constructNewEntry();
            var result = service.Insert(new Uri(BlogUrl), newPost);
            return result != null;
        }
        // Private Methods (1) 

        private AtomEntry constructNewEntry()
        {
            var newPost = new AtomEntry
            {
                Title = { Text = PostTitle },
                Content = new AtomContent
                {
                    Content = string.Format(@"<div xmlns=""http://www.w3.org/1999/xhtml"">{0}</div>", PostBody),
                    Type = "xhtml"
                },
                IsDraft = PostAsDraft
            };

            foreach (var tag in PostTags)
            {
                if (string.IsNullOrEmpty(tag)) continue;

                newPost.Categories.Add(
                    new AtomCategory
                    {
                        Term = tag.Trim(),
                        Scheme = "http://www.blogger.com/atom/ns#"
                    });
            }

            return newPost;
        }

        #endregion Methods
    }
}
